//
//  MSInviteFriendsViewController.m
//  SocietySale
//
//  Created by yumingwei on 2016/11/27.
//  Copyright © 2016年 Mike. All rights reserved.
//

#import "MSInviteFriendsViewController.h"
#import <AddressBook/AddressBook.h>
#import <Contacts/Contacts.h>
#import "SYContacter.h"
#import "NSString+SY.h"
#import "SYContactsHelper.h"

#import "MSJoindViewController.h"

@interface MSInviteFriendsViewController ()<UITableViewDataSource, UITableViewDelegate> {
@private
    NSMutableArray *_arrContacts;
}
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) NSMutableArray *selectedArray;
@property (nonatomic, strong) NSMutableArray *resultArray;
@property (nonatomic, strong) NSMutableArray *contactsArray;
@property (nonatomic, strong) UITableView    *tableView;
@end

@implementation MSInviteFriendsViewController

- (void)initNavigationBar{
    [super initNavigationBar];
    leftBarBtn.hidden = NO;
    rightBarBtn.hidden = NO;
    titleLable.text = @"邀请通讯录好友";
    
    rightBarBtn.frame = CGRectMake(SCREEN_WIDTH-80, 20, 80, 44);
    rightBarBtn.titleLabel.font = HeitiFont(14);
    rightBarBtn.titleLabel.textAlignment = NSTextAlignmentRight;
    [rightBarBtn setTitle:@"邀请（0）" forState:UIControlStateNormal];
}

- (void)initUI{
    _selectedArray = [NSMutableArray arrayWithCapacity:0];
    _resultArray = [NSMutableArray arrayWithCapacity:0];
    _contactsArray = [NSMutableArray arrayWithCapacity:0];
    __weak MSInviteFriendsViewController *weakSelf = self;
    
    NSUserDefaults *defaultes = [NSUserDefaults standardUserDefaults];
    NSString *uploadflag = [defaultes objectForKey:UploadContactsSuccess];
    if (uploadflag.length) {
        [netEngine requestUnjoinedFriendsWithTarget:self.VctrID hudView:self.contentView];
    }
    else{
        [SYContactsHelper fetchContacts:^(NSArray <SYContacter *> *contacts, BOOL success) {
            if (success) {
                for (SYContacter *contacter in contacts) {
                    NSDictionary *dict = @{@"name":[HDUtil check:contacter.name],@"mobile":[HDUtil check:contacter.phone]};
                    [_contactsArray addObject:dict];
                }
                
                [weakSelf uploadContactsWithArray:_contactsArray];
            }
            else {
                [weakSelf showUserDenied];
            }
        }];
    }
//    [SYContactsHelper fetchContacts:^(NSArray <SYContacter *> *contacts, BOOL success){
//        if (success) {
//            for (SYContacter *contacter in contacts) {
//                NSDictionary *dict = @{@"name":[HDUtil check:contacter.name],@"mobile":[HDUtil check:contacter.phone]};
//                [_contactsArray addObject:dict];
//            }
//        }
//    }];
}

- (void)uploadContactsWithArray:(NSArray*)array{
    NSData *data = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:nil];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    [netEngine requestUploadContactsWithTarget:self.VctrID hudView:self.contentView params:dic];
}

- (void)rightBarBtnAction{
//    NSData *data = [NSJSONSerialization dataWithJSONObject:@[@{@"ids":@"22"}] options:NSJSONWritingPrettyPrinted error:nil];
//    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSArray *selectedContacts = [self savedContacts];
    if (selectedContacts.count > 0) {
        if (selectedContacts.count < 5)
        {
            [HDUtil showMessage:@"请邀请至少5个联系人"];
            return;
        }
        NSMutableArray *idsArray = [NSMutableArray arrayWithCapacity:0];
        for (SYContacter *contacter in selectedContacts) {
            [idsArray addObject:contacter.phone];
        }
        NSString *idsStr = [idsArray componentsJoinedByString:@","];
        [netEngine requestInviteFriendsWithTarget:self.VctrID hudView:self.contentView params:idsStr];
//        if (self.delegate && [self.delegate respondsToSelector:@selector(contactsPickerController:didFinishPickingContacts:)]) {
//            [self.delegate contactsPickerController:self didFinishPickingContacts:selectedContacts];
//        }
        
    }
    else {
        [HDUtil showMessage:@"还未选择联系人!"];
    }
}

- (void)testDataFunc{
    NSArray *array = @[@{@"name":@"王的辉",@"mobile":@"1374345345"},@{@"name":@"李个志",@"mobile":@"18598893483"}];
    NSData *data = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:nil];
//    NSString *jsonString=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
//    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
}

- (void)updateViewController:(NSNotification *)note {
    NSDictionary *responseDic = note.userInfo;
    if (responseDic[Receiver]==self.VctrID) {
        if (responseDic[@"UploadContactsSuccess"]!=nil){
            NSUserDefaults *defaultes = [NSUserDefaults standardUserDefaults];
            [defaultes setObject:UploadContactsSuccess forKey:UploadContactsSuccess];
            [defaultes synchronize];
            
            [netEngine requestUnjoinedFriendsWithTarget:self.VctrID hudView:self.contentView];
        }
        if (responseDic[@"UnjoinedFriends"]!=nil){
            NSArray *dataArray = responseDic[@"UnjoinedFriends"];
            [self reloadContacts:dataArray];
            _titleLabel.text = [NSString stringWithFormat:@"已加入联系人（%@）",responseDic[@"registeredCount"]];
        }
        if (responseDic[@"InviteFriends"]!=nil){
            NSArray *selectedContacts = [self savedContacts];
            if (self.delegate && [self.delegate respondsToSelector:@selector(contactsPickerController:didFinishPickingContacts:)]) {
                [self.delegate contactsPickerController:self didFinishPickingContacts:selectedContacts];
            }
            [HDUtil showMessage:@"邀请成功"];
            
            if (self.isRegist) {
                [rootNavigation popToRootViewControllerAnimated:NO];
            }
            else{
                [rootNavigation popViewControllerAnimated:YES];
            }
        }
    }
}

- (NSArray *)savedContacts {
    NSMutableArray *contacts = [[NSMutableArray alloc] init];
    for (NSArray *section in _arrContacts) {
        for (SYContacter *contacter in section) {
            if (contacter.selected)
                [contacts addObject:contacter];
        }
    }
    
    return contacts;
}

- (void)reloadContacts:(NSArray *)contactsTemp {
    if (!_arrContacts) {
        _arrContacts = [[NSMutableArray alloc] init];
    }
    
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.contentView.bounds style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = kDefaultViewBackgroundColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.contentView addSubview:_tableView];
        
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 80)];
        headerView.backgroundColor = kDefaultViewBackgroundColor;
        _tableView.tableHeaderView = headerView;
        
        UIView *horizonLineView =[[UIView alloc] initWithFrame:CGRectMake(0, 50, SCREEN_WIDTH, 0.6)];
        horizonLineView.backgroundColor = kNormalGray;
        [headerView addSubview:horizonLineView];
        
        UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
        bgView.backgroundColor = [UIColor whiteColor];
        [headerView addSubview:bgView];
        
        _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(12, 0, SCREEN_WIDTH-12, 50)];
        _titleLabel.font = HeitiFont(15);
        _titleLabel.textColor = [UIColor blackColor];
        _titleLabel.text = @"已加入联系人（0）";
        _titleLabel.userInteractionEnabled = YES;
        [bgView addSubview:_titleLabel];
        
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick)];
        [_titleLabel addGestureRecognizer:tapGesture];
        
        UIImageView *arrow = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-20, 17, 8.5, 16.5)];
        arrow.image = [UIImage imageNamed:@"arrow2"];
        [bgView addSubview:arrow];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(12, 50, SCREEN_WIDTH, 30)];
        label.font = HeitiFont(12);
        label.textColor = kDarkGrayColor;
        label.text = @"首次邀请5个联系人加入可获得高级会员资格";
        [headerView addSubview:label];
        
        UIView *footerView = [[UIView alloc] init];
        footerView.backgroundColor = kDefaultViewBackgroundColor;
        _tableView.tableFooterView = footerView;
    }
    
    UILocalizedIndexedCollation *theCollation = [UILocalizedIndexedCollation currentCollation];
    for (SYContacter *contacter in contactsTemp) {
        NSInteger sect = [theCollation sectionForObject:contacter
                                collationStringSelector:@selector(getContacterName)];
        contacter.section = sect;
    }
    
    NSInteger highSection = [[theCollation sectionTitles] count];
    NSMutableArray *sectionArrays = [NSMutableArray arrayWithCapacity:highSection];
    for (NSInteger i = 0; i <= highSection; i++) {
        NSMutableArray *sectionArray = [NSMutableArray arrayWithCapacity:1];
        [sectionArrays addObject:sectionArray];
    }
    
    for (SYContacter *addressBook in contactsTemp) {
        [(NSMutableArray *)[sectionArrays objectAtIndex:addressBook.section] addObject:addressBook];
    }
    
    //getContactName 如果这个返回的是nil会有问题
    for (NSMutableArray *sectionArray in sectionArrays) {
        NSArray *sortedSection = [theCollation sortedArrayFromArray:sectionArray collationStringSelector:@selector(getContacterName)];
        [_arrContacts addObject:sortedSection];
    }
    [self.tableView reloadData];
}

- (void)tapClick{
    MSJoindViewController  *vc = [[MSJoindViewController alloc] init];
    [rootNavigation pushViewController:vc animated:YES];
}

- (void)onClickBtnSetting:(UIButton *)btn {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=General"]];
}

- (void)showUserDenied {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
    label.textAlignment = NSTextAlignmentCenter;
    label.numberOfLines = 0;
    label.textColor = [UIColor redColor];
    [self.view addSubview:label];
    
    NSString *str = [NSString stringWithFormat:@"您没有权限访问通讯录\n\n请到“设置-隐私-通讯录”里\n允许”销傲江湖“访问"];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];
    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20.0] range:[str rangeOfString:@"您没有权限访问通讯录"]];
    label.attributedText = attributedString;
    [label sizeToFit];
    label.frame = CGRectMake(0, 0, label.frame.size.width, label.frame.size.height);
    label.center = CGPointMake(self.view.frame.size.width / 2, self.view.frame.size.height / 2);
    
    UIButton *settingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    settingBtn.frame = CGRectMake(0, 0, 140, 40);
    settingBtn.backgroundColor = [UIColor blueColor];
    settingBtn.layer.cornerRadius = 5;
    settingBtn.layer.masksToBounds = YES;
    [settingBtn setTitle:@"去设置" forState:UIControlStateNormal];
    [settingBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    settingBtn.center = CGPointMake(self.view.frame.size.width / 2, label.center.y + 5 + 20 + label.frame.size.height / 2);
    [settingBtn addTarget:self action:@selector(onClickBtnSetting:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:settingBtn];
}

- (void)checkButtonTapped:(id)sender event:(id)event {
    NSSet *touches = [event allTouches];
    UITouch *touch = [touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];
    
    if (indexPath) {
        [self accessoryButtonTappedForRowWithIndexPath:indexPath];
    }
}

- (void)accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
    SYContacter *contacter = (SYContacter *)[[_arrContacts objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    
    BOOL checked = !contacter.selected;
    contacter.selected = checked;
    
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    UIButton *button = (UIButton *)cell.accessoryView;
    [button setSelected:checked];
    
    [_selectedArray removeAllObjects];
    for (int i = 0; i<_arrContacts.count; i++) {
        NSArray *array = _arrContacts[i];
        for (int j = 0; j<array.count; j++){
            SYContacter *contacter = array[j];
            if (contacter.selected) {
                [_selectedArray addObject:@"yes"];
            }
        }
    }
    NSString *selectNum = [NSString stringWithFormat:@"邀请（%lD）",_selectedArray.count];
    [rightBarBtn setTitle:selectNum forState:UIControlStateNormal];
}

#pragma mark -
#pragma mark UITableViewDataSource & UITableViewDelegate

//- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
//    return [[NSArray array] arrayByAddingObjectsFromArray:
//            [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles]];
//}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    return [[UILocalizedIndexedCollation currentCollation] sectionForSectionIndexTitleAtIndex:index];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [_arrContacts count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [[_arrContacts objectAtIndex:section] count] ? [[[UILocalizedIndexedCollation currentCollation] sectionTitles] objectAtIndex:section] : nil;
}

-(void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    view.tintColor = [UIColor whiteColor];
    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
    header.contentView.backgroundColor=kDefaultViewBackgroundColor;
    header.textLabel.font = HeitiFont(15);
    header.textLabel.textColor = kDarkGrayColor;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return [[_arrContacts objectAtIndex:section] count] ? tableView.sectionHeaderHeight : 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[_arrContacts objectAtIndex:section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *kCellID = @"kCellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellID];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        UIView *horizonLineView =[[UIView alloc] initWithFrame:CGRectMake(12, 43.4, SCREEN_WIDTH, 0.6)];
        horizonLineView.backgroundColor = kNormalGray;
        horizonLineView.tag = 100+indexPath.row;
        [cell.contentView addSubview:horizonLineView];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setFrame:CGRectMake(30, 0, 15, 15)];
        [button setBackgroundImage:[UIImage imageNamed:@"select0"] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@"select1"] forState:UIControlStateSelected];
        [button addTarget:self action:@selector(checkButtonTapped:event:) forControlEvents:UIControlEventTouchUpInside];
        [button setSelected:NO];
        cell.accessoryView = button;
    }
    
    SYContacter *addressBook = (SYContacter *)[[_arrContacts objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    
    cell.textLabel.font = HeitiFont(15);
    if ([[addressBook.name sy_trim] length] > 0) {
        cell.textLabel.text = addressBook.name;
    }
    else {
        cell.textLabel.font = [UIFont italicSystemFontOfSize:cell.textLabel.font.pointSize];
        cell.textLabel.text = @"未填写";
    }
    
    UIButton *button = (UIButton *)cell.accessoryView;
    [button setSelected:addressBook.selected];
    
    UIView *horizonLineView = [cell viewWithTag:100+indexPath.row];
    if (indexPath.row == [[_arrContacts objectAtIndex:indexPath.section] count] -1) {
        horizonLineView.frame = CGRectMake(0, 43.4, SCREEN_WIDTH, 0.6);
    }
    else{
        horizonLineView.frame = CGRectMake(12, 43.4, SCREEN_WIDTH-24, 0.6);
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.delegate && [self.delegate respondsToSelector:@selector(contactsPickerController:didSelectRowAtIndexPath:)]) {
        [self.delegate contactsPickerController:self didSelectRowAtIndexPath:indexPath];
    }
    
    SYContacter *contacter = (SYContacter *)[[_arrContacts objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(contactsPickerController:didSelectContacter:)]) {
        [self.delegate contactsPickerController:self didSelectContacter:contacter];
    }
    
    [self accessoryButtonTappedForRowWithIndexPath:indexPath];
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
